//
// Created by goksu on 2/25/20.
//

#include <fstream>
#include "Scene.hpp"
#include "Renderer.hpp"


inline float deg2rad(const float& deg) { return deg * M_PI / 180.0; }

const float EPSILON = 0.00001;

// The main render function. This where we iterate over all pixels in the image,
// generate primary rays and cast these rays into the scene. The content of the
// framebuffer is saved to a file.
void Renderer::Render(const Scene& scene, int sig)
{
    float scale = tan(deg2rad(scene.fov * 0.5));
    float imageAspectRatio = scene.width / (float)scene.height;
    Vector3f eye_pos(278, 273, -800);

    // change the spp value to change sample ammount
    extern int spp;

    for (uint32_t j = 0; j < scene.height; ++j) {
        for (uint32_t i = 0; i < scene.width; ++i) {
            // generate primary ray direction
            if(((j+i) % 4) != sig){
                continue;
            }
            for(int k = 0; k < spp; ++k){
            float x = (2 * (i + get_random_float()) / (float)scene.width - 1) *
                      imageAspectRatio * scale;
            float y = (1 - 2 * (j + get_random_float()) / (float)scene.height) * scale;

            Vector3f dir = normalize(Vector3f(-x, y, 1));
            framebuffer[j * scene.width + i] += scene.castRay(Ray(eye_pos, dir), 0) / spp;  
            }
        }
        UpdateProgress(j / (float)scene.height, sig);
    }
    UpdateProgress(1.f, sig);

    // save framebuffer to file
 
}

Renderer::Renderer(int size){
    framebuffer.resize(size);
}